﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

public partial class ViewEpisode : System.Web.UI.Page
{
    ManageDatabase data;
    Episode episode;
    Season season;
    Serie series;
    List<Comment> comments;
    Comment newComment;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (data == null)
        {
            data = new ManageDatabase();
        }
        if (!IsPostBack)
        {
            if (Request.QueryString["epizod"] != null)
            {
                String s = Request.QueryString["epizod"].ToString();
                Initialize(Convert.ToInt32(s));
            }
            else
            {
                Response.Redirect("Series.aspx");
            }
        }
    }

    private void Initialize(int episodeId)
    {
        try
        {
            episode = data.GetWholeEpisode(episodeId, true);
            season = data.GetWholeSeason(episode.seasonId, true);
            series = data.GetWholeSerie(episode.seriesId, true);

            if (!User.IsInRole("admin") && Functions.GetUserId() != episode.userID && episode.status != 1)
            {
                Response.Redirect("~/Default.aspx");
            }

            //EpisodePanel.CssClass = "panel";
            EpisodeInfo.CssClass = "infoTalbe";
            EpisodeHunTitle.CssClass = "titleHun";
            EpisodeOrigTitle.CssClass = "titleOrig";
            EpisodeStatus.CssClass = "status";
            EpisodeLength.CssClass = "length";
            EpisodeReleaseDate.CssClass = "releaseDate";
            EpisodeDescription.CssClass = "description";
            EpisodeDirectors.CssClass = "directors";
            EpisodeWriters.CssClass = "writers";
            EpisodeStars.CssClass = "stars";
            EpisodeGenres.CssClass = "genres";

            if (season.status != 1)
            {
                EpisodeStatus.Text = "   (Nem engedélyezett)";
            } 

            if (episode.imgUrl != "")
                EpisodeImg.ImageUrl = "~/Pic/" + episode.imgUrl;
            else
                EpisodeImg.ImageUrl = "~/images/nopic.png";
            EpisodeImg.Width = 300;
            EpisodeImg.Height = 300;
            EpisodeHunTitle.Text = episode.titleHun + " (" + episode.episode.ToString() + ". Epizód)";
            EpisodeOrigTitle.Text = episode.titleOrig + " (" + "Eposode " + episode.episode.ToString() + ")";
            EpisodeSeries.Text = series.titleHun;
            EpisodeSeries.NavigateUrl = "Seasons.aspx?sorozat=" + series.id.ToString();
            EpisodeSeason.Text = season.season + ". Évad";
            EpisodeSeason.NavigateUrl = "Episodes.aspx?evad=" + season.id.ToString();
            EpisodeDirectors.Text = series.directors;
            EpisodeWriters.Text = series.writers;
            EpisodeStars.Text = series.stars;
            EpisodeReleaseDate.Text = String.Format("{0:yyyy.MM.dd}", episode.releaseDate);
            EpisodeDescription.Text = episode.description;

            if (Convert.ToInt32(episode.length) != 0)
            {
                string length = "N/A";
                int seconds = Convert.ToInt32(episode.length);
                int hours = 0, minutes = 0;

                hours = seconds / 3600;
                if (hours == 0)
                {
                    minutes = seconds / 60;
                    if (minutes == 0)
                    {
                        length = seconds.ToString() + " másodperc";
                    }
                    else {
                        seconds = seconds - minutes * 60;
                        length = minutes.ToString() + " perc " + seconds.ToString() + " másodperc";
                    }
                }
                else {
                    minutes = (seconds - hours * 3600) / 60;
                    seconds = seconds - hours * 3600 - minutes * 60;
                    length = hours.ToString() + " óra " + minutes.ToString() + " perc " + seconds.ToString() + " másodperc";
                }

                EpisodeLength.Text = length;
            }
            else {
                EpisodeLength.Text = "N/A";
            }

            foreach (ListItem genre in series.genres)
            {
                EpisodeGenres.Text += genre.Text + ", ";
            }
            if (EpisodeGenres.Text.Length > 0)
                EpisodeGenres.Text = EpisodeGenres.Text.Substring(0, EpisodeGenres.Text.Length - 2);

            if (User.IsInRole("admin"))
            {
                toolDiv.Visible = true;
                EditButton.Visible = true;
                DeleteButton.Visible = true;
                if (episode.status == 1)
                {
                    StatusMinusButton.Visible = true;
                    StatusPlusButton.Visible = false;
                }
                else
                {
                    StatusMinusButton.Visible = false;
                    StatusPlusButton.Visible = true;
                }
            }
            else if (User.IsInRole("user") && Functions.GetUserId().Equals(episode.userID))
            {
                toolDiv.Visible = true;
                EditButton.Visible = true;
                DeleteButton.Visible = false;
            }
            else
            {
                toolDiv.Visible = false;
                EditButton.Visible = false;
                DeleteButton.Visible = false;
            }

            CreateListComments();
        }
        catch (Exception)
        {

        }
    }

    protected void CommentSubmit_Click(object sender, EventArgs e) {
        newComment = new Comment();
        if (CommentContent.Text == "")
        {
            Alert.Show("A hozzászólás szövege nem lehet üres!");
            return;
        }
        else {
            String s = Request.QueryString["epizod"].ToString();
            episode = data.GetWholeEpisode(Convert.ToInt32(s), true);

            newComment.seriesId = episode.seriesId;
            newComment.seasonId = episode.seasonId;
            newComment.episodeId = episode.id;
            newComment.title = CommentTitle.Text;
            newComment.content = CommentContent.Text;
            newComment.userId = Functions.GetUserId();  

            Boolean success = data.InsertComment(newComment);

            if (!success)
            {
                Alert.Show("Hiba történt a hozzászólás létrehozása során!");
            }
            else {
                CommentTitle.Text = "";
                CommentContent.Text = "";
                CommentPanelList.Controls.Clear();
                CreateListComments();
            }
        }
    }

    private void CreateListComments()
    {
        try
        {
            comments = data.GetComments(episode.seriesId, episode.seasonId, episode.id);


            foreach (Comment item in comments)
            {
                Panel CommentPanel = new Panel();
                HtmlGenericControl FieldSet = new HtmlGenericControl("fieldset");
                Table CommentTable = new Table();
                TableRow CommentRow = new TableRow();
                TableCell CommentCellLeft = new TableCell();
                TableCell CommentCellRight = new TableCell();
                Table CommentPicTable = new Table();
                TableRow CommentPic1Row = new TableRow();
                TableCell CommentPic1Cell = new TableCell();
                TableRow CommentPic2Row = new TableRow();
                TableCell CommentPic2Cell = new TableCell();
                Table CommentInfoTable = new Table();
                TableRow CommentInfo1Row = new TableRow();
                TableCell CommentInfo1Cell = new TableCell();
                TableRow CommentInfo2Row = new TableRow();
                TableCell CommentInfo2Cell = new TableCell();
                TableRow CommentInfo3Row = new TableRow();
                TableCell CommentInfo3Cell = new TableCell();

                Image ThumbImage = new Image();
                Label CreatedDate = new Label();
                Label UserName = new Label();
                Label Title = new Label();
                Label Content = new Label();

                CommentPanel.ID = "CommentPanel" + item.id.ToString();
                CommentTable.ID = "CommentTable" + item.id.ToString();
                CommentRow.ID = "CommentRow" + item.id.ToString();
                CommentCellLeft.ID = "CommentCellLeft" + item.id.ToString();
                CommentCellRight.ID = "CommentCellRight" + item.id.ToString();
                ThumbImage.ID = "ThumbImage" + item.id.ToString();
                CreatedDate.ID = "CreatedDate" + item.id.ToString();
                UserName.ID = "UserName" + item.id.ToString();
                Title.ID = "Title" + item.id.ToString();
                Content.ID = "Content" + item.id.ToString();

                CommentPanel.CssClass = "commentPanel";
                CommentTable.CssClass = "commentTable";
                CommentCellLeft.CssClass = "commentTableLeft";
                CommentCellRight.CssClass = "commentTableRight";
                CommentInfoTable.CssClass = "commentInfoTable";
                CreatedDate.CssClass = "commentCreatedDate";
                UserName.CssClass = "commentUserName";
                Title.CssClass = "commentTitle";
                Content.CssClass = "commentContent";

                ThumbImage.ImageUrl = "~/images/nopic.gif";
                ThumbImage.Width = 80;
                ThumbImage.Height = 80;
                UserName.Text = data.GetUserById(item.userId);
                CreatedDate.Text = String.Format("{0:yyyy.MM.dd HH:mm:ss}", item.createdDate);
                Title.Text = item.title;
                Content.Text = item.content;

                CommentPic1Cell.HorizontalAlign = HorizontalAlign.Center;
                CommentPic2Cell.HorizontalAlign = HorizontalAlign.Center;
                CommentInfo1Cell.HorizontalAlign = HorizontalAlign.Right;

                CommentCellLeft.VerticalAlign = VerticalAlign.Top;
                CommentCellRight.VerticalAlign = VerticalAlign.Top;

                CommentPic1Cell.Controls.Add(ThumbImage);
                CommentPic2Cell.Controls.Add(UserName);
                CommentInfo1Cell.Controls.Add(CreatedDate);
                CommentInfo2Cell.Controls.Add(Title);
                CommentInfo3Cell.Controls.Add(Content);

                CommentPic1Row.Controls.Add(CommentPic1Cell);
                CommentPic2Row.Controls.Add(CommentPic2Cell);
                CommentInfo1Row.Controls.Add(CommentInfo1Cell);
                CommentInfo2Row.Controls.Add(CommentInfo2Cell);
                CommentInfo3Row.Controls.Add(CommentInfo3Cell);

                CommentPicTable.Controls.Add(CommentPic1Row);
                CommentPicTable.Controls.Add(CommentPic2Row);
                CommentInfoTable.Controls.Add(CommentInfo1Row);
                CommentInfoTable.Controls.Add(CommentInfo2Row);
                CommentInfoTable.Controls.Add(CommentInfo3Row);

                CommentCellLeft.Controls.Add(CommentPicTable);
                CommentCellRight.Controls.Add(CommentInfoTable);

                CommentRow.Controls.Add(CommentCellLeft);
                CommentRow.Controls.Add(CommentCellRight);
                CommentTable.Controls.Add(CommentRow);
                FieldSet.Controls.Add(CommentTable);

                CommentPanelList.Controls.Add(FieldSet);
            }
        }
        catch (Exception) { 
        
        }
    }

    protected void StatusMinusButton_Click(object sender, EventArgs e)
    {
        String s = Request.QueryString["evad"].ToString();
        if (data.UpdateSeasonStatus(Convert.ToInt32(s), -1))
        {
            Initialize(Convert.ToInt32(s));
        }
        else
        {
            Alert.Show("A sorozatot nem sikerült letiltani!");
        }
    }

    protected void StatusPlusButton_Click(object sender, EventArgs e)
    {
        String s = Request.QueryString["epizod"].ToString();
        if (data.UpdateSeasonStatus(Convert.ToInt32(s), 1))
        {
            Initialize(Convert.ToInt32(s));
        }
        else
        {
            Alert.Show("Az epizódot nem sikerült engedélyezni!");
        }
    }

    protected void EditButton_Click(object sender, EventArgs e)
    {
        String s = Request.QueryString["epizod"].ToString();
        Response.Redirect("~/ModifyEpisode.aspx?epizod=" + s);
    }

    protected void DeleteButton_Click(object sender, EventArgs e)
    {
        String s = Request.QueryString["epizod"].ToString();
        if (data.DeleteEpisode(Convert.ToInt32(s)))
        {
            Response.Redirect("~/Series.aspx");
        }
        else
        {
            Alert.Show("A törlés során hiba lépett fel!");
        }
    }
    protected void Rating_Changed(object sender, EventArgs e)
    {

    }
}